// pages/patient/measuer-day/index.js
import Toast from "./../../../../miniprogram/miniprogram_npm/@vant/weapp/toast/toast";
import { post } from "./../../../../api/api";

Page({
  data: {
    timuList: [
      { id: 0, name: "temperature", title: "体温", desc: "体温曲线与预警", danwei: "℃" },
      { id: 1, name: "pressure", title: "血压", desc: "血压曲线与预警", danwei: "mmHg" },
      { id: 2, name: "bloodsugar", title: "血糖", desc: "血糖曲线与预警", danwei: "mmol/L" },
      { id: 3, name: "weight", title: "体重", desc: "BMI指数与预警", danwei: "kg" },
      { id: 4, name: "smoke", title: "吸烟", desc: "", danwei: "支/天" },
      { id: 5, name: "drink", title: "饮酒", desc: "", danwei: "ml/天" }
    ],
    ansList: null,
    openid: null,
    showOverLay: false, // 遮罩层
  },

  onLoad: async function (options) {
    console.log(options)

    let openid = wx.getStorageSync('openid');
    if (openid == "" || openid == null || openid == undefined) {
      // unlogin,has no openid
      Toast('unlogin')
      return;
    }
    let list = new Array(this.data.timuList.length);
    for (let i = 0; i < this.data.timuList.length; i++) {
      list[i] = { key: this.data.timuList[i].name, value: "-1" }
    }
    this.setData({
      ansList: list,
      openid: openid
    })
    // console.log(this.data.ansList)
  },

  // 子组件传值的时候将结果保存到数组
  handleGetInput: async function (ex) {
    let { value, key, id } = ex.detail;
    let tmplist = this.data.ansList;
    tmplist[Number(id)] = { key: key, value: value };
    this.setData({
      ansList: tmplist
    })
    // console.log(this.data.ansList);
  },

  postMeasureData: async function (sendData) {
    try {
      let pres = await post("/measure/dailyinput", sendData);
      if (pres.statusCode != 200)
        throw '网络错误';
      if (pres.data.rescode != 200) {
        if (pres.data.msg)
          throw `失败 ${pres.data.msg}`;
        else
          throw `失败`;
      }
      return '提交成功';
    } catch (error) {
      console.log(error);
      return error;
    }
  },

  // 提交
  handleSubmit: async function () {
    let openid = this.data.openid;
    if (openid == "" || openid == null || openid == undefined) {
      Toast('未登录');
      return;
    }
    let len = this.data.ansList.length;
    let alist = new Array(len);
    for (let i = 0; i < len; i++) {
      // console.log(this.data.ansList[i].value)
      alist[i] = (this.data.ansList[i].value);
    }
    let sendData = {
      openid: this.data.openid,
      ansList: alist,
    }
    console.log(sendData);
    this.setData({
      showOverLay: true
    })
    let res = await this.postMeasureData(sendData);
    if (res == '提交成功') {
      let storageList = wx.getStorageSync("planList");
      storageList[1].finish = true;
      wx.setStorageSync("planList", storageList);

      setTimeout(() => {
        wx.switchTab({
          url: '/pages/tarbarpages/home/index/index',
        })
      }, 500)
    }
    Toast(res);
    this.setData({
      showOverLay: false
    });
  }
})